package org.manusoft.refill.dao;

import java.util.List;
import java.util.Map;

import javax.persistence.Query;

import org.manusoft.refill.domain.TUserDetailsRf;
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl extends AbstractGenericJPADAO<TUserDetailsRf, Integer>
implements UserDao {

	

	@SuppressWarnings("unchecked")
	public TUserDetailsRf findByName(String username) {
		Query query = getEntityManager().createQuery("Select m from TUserDetailsRf m where m.userName = :username");
		query.setParameter("username", username );
		return (TUserDetailsRf) query.getSingleResult();
	}

    public List<TUserDetailsRf> loadLazy(int first, int pageSize, String sortField, String sortOrder, Map<String, String> filters){
        
        String where = "";
        for (Map.Entry<String, String> e : filters.entrySet())
            where += (where.length()>0 ? " AND " : "") + e.getKey() + " like '" + e.getValue() + "%'";
            
        Query lazy = getEntityManager().createQuery("Select m from TUserDetailsRf m" + (where.length() > 0 ? " where " +  where : "") + (sortField != null && sortOrder != null ? " order by " + sortField + " " + sortOrder : "") );
        lazy.setFirstResult(first);
        lazy.setMaxResults(pageSize);
        
        return lazy.getResultList();
    }

    
    public Long getRowCount(Map<String, String> filters) {
        String where = "";
        if(filters != null) {
            for (Map.Entry<String, String> e : filters.entrySet()) {
                where += (where.length()>0 ? " AND " : "") + e.getKey() + " like '" + e.getValue() + "%'";
            } 
        }
        
        return (Long)this.getEntityManager().createQuery("select count(*) from TUserDetailsRf m" + (where.length() > 0 ? " where " +  where : "")).getSingleResult();
    }
}